package com.im323.common.util;

import java.io.IOException;

import com.fasterxml.jackson.annotation.JsonInclude.Include;
import com.fasterxml.jackson.core.JsonParser.Feature;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.ObjectMapper;

public class JsonUtil {

	private static ObjectMapper mapper;

	public static ObjectMapper getMapper() {
		if (mapper == null) {
			mapper = new ObjectMapper();
			// 通过该方法对mapper对象进行设置，所有序列化的对象都将按改规则进行系列化
			// Include.ALWAYS 默认
			// Include.NON_DEFAULT 属性为默认值不序列化
			// Include.NON_EMPTY 属性为 空（“”） 或者为 NULL 都不序列化
			// Include.NON_NULL 属性为NULL 不序列化
			Include include = Include.NON_NULL;
			mapper.setSerializationInclusion(include);
			// 反序列化时， 忽略不存在的字段
			mapper = mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
			// 允许单引号
			mapper = mapper.configure(Feature.ALLOW_SINGLE_QUOTES, true);
			// 允许键不加引号
			mapper = mapper.configure(Feature.ALLOW_UNQUOTED_FIELD_NAMES, true);
		}
		return mapper;
	}

	/**
	 * obj转成json
	 * 
	 * @param obj
	 * @return
	 */
	public static String toJson(Object obj) {
		String str = null;
		try {
			str = getMapper().writeValueAsString(obj);
		} catch (Exception e) {
			e.printStackTrace();
		}
		return str;
	}

	/**
	 * obj转成json，并格式化
	 * 
	 * @param obj
	 * @return
	 */
	public static String toJsonFormat(Object obj) {
		String str = null;
		try {
			str = getMapper().writerWithDefaultPrettyPrinter().writeValueAsString(obj);
		} catch (JsonProcessingException e) {
			e.printStackTrace();
		}
		return str;
	}

	public static String formatJson(String jsonStr) {
		String str = null;
		try {
			Object json = mapper.readValue(jsonStr, Object.class);
			str = mapper.writerWithDefaultPrettyPrinter().writeValueAsString(json);
		} catch (IOException e) {
			e.printStackTrace();
		}
		return str;
	}

	public static <T> T toObj(String json, Class<T> clazz) {
		try {
			T obj = getMapper().readValue(json, clazz);
			return obj;
		} catch (Exception e) {
			e.printStackTrace();
		}
		return null;
	}

	public static <T> T toObj(String json, TypeReference<T> reference) {
		try {
			T obj = getMapper().readValue(json, reference);
			return obj;
		} catch (Exception e) {
			e.printStackTrace();
		}
		return null;
	}

}
